package github.sf.fw.utils;


import github.sf.fw.tools.ExtClassLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class ExtUtil {
    public final static String JAR_SUF_NAME = ".jar";
    private final static Logger logger = LoggerFactory.getLogger(ExtUtil.class);

    public static Class<?> loadClass(String name, String spi, String libPath) {
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        try {
            List<URL> jarsUrlsOfPath = getJarsUrlsOfPath(libPath);
            ExtClassLoader extClassLoader = new ExtClassLoader(name, jarsUrlsOfPath.toArray(new URL[0]), contextClassLoader);
            Thread.currentThread().setContextClassLoader(extClassLoader);
            return extClassLoader.loadClass(spi);
        } catch (MalformedURLException e) {
            logger.error("{}路径错误", libPath, e);
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            logger.error("没有找到{}类", spi, e);
            throw new RuntimeException(e);
        } finally {
            Thread.currentThread().setContextClassLoader(contextClassLoader);
        }
    }

    public static List<String> getJarsOfPath(String path) {
        File file = new File(path);
        List<String> jars = new ArrayList<>();
        if (file.listFiles() != null) {
            for (File f : file.listFiles()) {
                // only search from dss-xxxxx.jar.
                if (!f.isDirectory() && f.getName().endsWith(JAR_SUF_NAME) && f.getName().startsWith("dss-")) {
                    jars.add(f.getPath());
                }
            }
        }
        return jars;
    }


    public static List<URL> getJarsUrlsOfPath(String path) throws MalformedURLException {
        File file = new File(path);
        List<URL> jars = new ArrayList<>();
        if (file.listFiles() != null) {
            for (File f : file.listFiles()) {
                if (!f.isDirectory() && f.getName().endsWith(JAR_SUF_NAME)) {
                    jars.add(f.toURI().toURL());
                }
            }
        }
        return jars;
    }
}
